const Router = require('koa-router')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const dotenv = require('dotenv')
const { User, Role, Permission } = require('../models')

// 确保环境变量被加载
dotenv.config({ path: '../../.env' })

const router = new Router({ prefix: '/api/auth' })

// 登录
router.post('/login', async (ctx) => {
  const { username, password } = ctx.request.body
  
  // 清理输入数据，去除前后空格
  const cleanUsername = username ? username.trim() : ''
  const cleanPassword = password ? password.trim() : ''

  if (!cleanUsername || !cleanPassword) {
    ctx.status = 400
    ctx.body = {
      success: false,
      message: '用户名和密码不能为空'
    }
    return
  }

  try {
    // 查找用户并包含角色和权限信息
    const user = await User.findOne({
      where: { username: cleanUsername, status: 'active' },
      include: [{
        model: Role,
        as: 'roles',
        include: [{
          model: Permission,
          as: 'permissions',
          through: { attributes: [] }
        }],
        through: { attributes: [] }
      }]
    })

    if (!user) {
      ctx.status = 401
      ctx.body = {
        success: false,
        message: '用户名或密码错误'
      }
      return
    }

    // 验证密码
    const isValidPassword = await bcrypt.compare(cleanPassword, user.password)
    if (!isValidPassword) {
      ctx.status = 401
      ctx.body = {
        success: false,
        message: '用户名或密码错误'
      }
      return
    }

    // 更新登录信息
    await user.update({
      last_login_at: new Date(),
      login_count: user.login_count + 1
    })

    // 生成JWT Token
    const token = jwt.sign(
      { 
        userId: user.id, 
        username: user.username,
        roles: user.roles.map(role => role.code)
      },
      process.env.JWT_SECRET || 'xSynergyOs_JWT_Secret_Key_2024',
      { expiresIn: process.env.JWT_EXPIRE || '24h' }
    )

    // 提取所有权限
    const permissions = []
    user.roles.forEach(role => {
      role.permissions.forEach(permission => {
        if (!permissions.includes(permission.code)) {
          permissions.push(permission.code)
        }
      })
    })

    ctx.body = {
      success: true,
      message: '登录成功',
      data: {
        user: {
          id: user.id,
          username: user.username,
          email: user.email,
          realName: user.real_name,
          phone: user.phone,
          avatar: user.avatar,
          roles: user.roles.map(role => ({
            id: role.id,
            name: role.name,
            code: role.code,
            description: role.description,
            permissions: role.permissions.map(p => ({
              id: p.id,
              name: p.name,
              code: p.code,
              resource: p.resource,
              action: p.action
            }))
          })),
          status: user.status,
          lastLoginAt: user.last_login_at
        },
        token,
        permissions
      }
    }
  } catch (error) {
    console.error('Login error:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '登录失败，请稍后重试'
    }
  }
})

// 获取当前用户信息
router.get('/me', async (ctx) => {
  try {
    const userId = ctx.state.user.userId
    
    const user = await User.findByPk(userId, {
      include: [{
        model: Role,
        as: 'roles',
        include: [{
          model: Permission,
          as: 'permissions',
          through: { attributes: [] }
        }],
        through: { attributes: [] }
      }]
    })

    if (!user) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: '用户不存在'
      }
      return
    }

    const permissions = []
    user.roles.forEach(role => {
      role.permissions.forEach(permission => {
        if (!permissions.includes(permission.code)) {
          permissions.push(permission.code)
        }
      })
    })

    ctx.body = {
      success: true,
      data: {
        user: {
          id: user.id,
          username: user.username,
          email: user.email,
          realName: user.real_name,
          phone: user.phone,
          avatar: user.avatar,
          roles: user.roles,
          status: user.status,
          lastLoginAt: user.last_login_at
        },
        permissions
      }
    }
  } catch (error) {
    console.error('Get user info error:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '获取用户信息失败'
    }
  }
})

// 刷新Token
router.post('/refresh', async (ctx) => {
  try {
    // 从Authorization header获取旧token并解码
    const authHeader = ctx.headers.authorization
    const token = authHeader && authHeader.split(' ')[1]
    
    if (!token) {
      ctx.status = 401
      ctx.body = {
        success: false,
        message: 'Token缺失'
      }
      return
    }

    // 验证旧token（即使过期也要能解码出用户信息）
    let decoded
    try {
      decoded = jwt.verify(token, process.env.JWT_SECRET || 'xSynergyOs_JWT_Secret_Key_2024')
    } catch (err) {
      // 如果token过期，使用ignoreExpiration选项重新解码
      if (err.name === 'TokenExpiredError') {
        decoded = jwt.verify(token, process.env.JWT_SECRET || 'xSynergyOs_JWT_Secret_Key_2024', { ignoreExpiration: true })
      } else {
        throw err
      }
    }
    
    const userId = decoded.userId
    
    const user = await User.findByPk(userId, {
      include: [{
        model: Role,
        as: 'roles',
        through: { attributes: [] }
      }]
    })

    if (!user || user.status !== 'active') {
      ctx.status = 401
      ctx.body = {
        success: false,
        message: '用户状态异常'
      }
      return
    }

    // 生成新的Token
    const newToken = jwt.sign(
      { 
        userId: user.id, 
        username: user.username,
        roles: user.roles.map(role => role.code)
      },
      process.env.JWT_SECRET || 'xSynergyOs_JWT_Secret_Key_2024',
      { expiresIn: process.env.JWT_EXPIRE || '24h' }
    )

    ctx.body = {
      success: true,
      message: 'Token刷新成功',
      data: { token: newToken }
    }
  } catch (error) {
    console.error('Refresh token error:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: 'Token刷新失败'
    }
  }
})

// 登出
router.post('/logout', async (ctx) => {
  // 这里可以实现Token黑名单等逻辑
  ctx.body = {
    success: true,
    message: '登出成功'
  }
})

module.exports = router